#include "hashmap.h"

#include "../xkit.h"

MapHeader *MapInit(losu_vm_t vm) {
    MapHeader *h = __xkit_malloc(sizeof(MapHeader));
    h->umap = obj_newunit(vm, obj_unittype_unit);
    vm_lock(vm, &(h->umap));
    return h;
}

void MapFree(losu_vm_t vm, MapHeader *h) {
    vm_unlock(vm, &(h->umap));
    __xkit_free(h);
}

void MapPut(losu_vm_t vm, MapHeader *h, losu_object_t key, losu_object_t value) {
    obj_unitset(vm, h->umap, *key, *value);
}

void MapGet(losu_vm_t vm, MapHeader *h, losu_object_t key, losu_object_t target) {
    *target = *obj_unitindex(vm, h->umap, *key);
}

void MapRemove(losu_vm_t vm, MapHeader *h, losu_object_t key) {
    obj_unitset(vm, h->umap, *key, obj_newfalse(vm));
}

bool MapExists(losu_vm_t vm, MapHeader *h, losu_object_t key) {
    losu_object_t target = obj_unitindex(vm, h->umap, *key);
    if (target == NULL || target->type == losu_object_type_false) {
        return false;
    }
    return true;
}

size_t MapSize(losu_vm_t vm, MapHeader *h) {
    return obj_unitsize(vm, h->umap);
}
